﻿using System;
using System.Linq;
using System.ServiceProcess;
using Clancy.Bl;
using Clancy.Bl.VideoProvider;
using Clancy.Interfaces;
using Clancy.Service.Base;
using Ninject;

namespace Clancy.Service.Executable
{
    public partial class ClancyService : ServiceBase
    {
        private const string c_SurveilanceConfigFile = "SurveilanceConfigService.xml";
        private StandardKernel m_Kernel;
        private IServiceController m_ServiceController;
        private ISurveilanceLogic m_SurveilanceLogic;

        public ClancyService()
        {
            InitializeComponent();

            PrepareService();
        }

        private void PrepareService()
        {
            m_Kernel = new StandardKernel();
            
            RegisterServices(m_Kernel);

            m_ServiceController = m_Kernel.Get<IServiceController>();
            m_SurveilanceLogic = m_Kernel.Get<ISurveilanceLogic>();
        }

        protected override void OnStart(string[] args)
        {
            m_SurveilanceLogic.LoadConfiguration(c_SurveilanceConfigFile);
            m_ServiceController.OpenCommunicationService("127.0.0.1", 65432);
            m_ServiceController.StartSurveilance();
        }

        protected override void OnStop()
        {
            m_ServiceController.StopSurveilance();
            m_SurveilanceLogic.SaveConfiguration(c_SurveilanceConfigFile);
        }

        private static void RegisterServices(StandardKernel kernel)
        {
            kernel.Load<BlCatalog>();
            kernel.Load<ServiceCatalog>();
            kernel.Load<VideoProviderCatalog>();
        }

        private void DisposeSurveilance()
        {
            m_SurveilanceLogic.Dispose();
            m_ServiceController.Dispose();
            m_ServiceController.Dispose();
        }
    }
}
